package bootstrap

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
	"log"
	"os"
	"strconv"
	"time"
)


type Configurator func(*App)

type App struct {
	*iris.Application
	AppName      string
	AppSpawnDate time.Time
}

func (app *App) Configure(configurators ...Configurator) *App {
	for _, cfg := range configurators {
		cfg(app)
	}
	return app
}

func (app *App)SetupViews(){
	htmlEngine := iris.HTML("./views", ".html")
	//热加载模板
	htmlEngine.Reload(true)
	app.RegisterView(htmlEngine)
}

func (app *App) SetupErrorHandlers() {

	app.OnAnyErrorCode(func(ctx iris.Context) {

		switch ctx.GetStatusCode() {
		case iris.StatusNotFound:
			ctx.View("errors/404.html")
		case iris.StatusForbidden:
			ctx.View("errors/403.html")
		case iris.StatusBadGateway:
			ctx.View("errors/502.html")
		default:
			ctx.View("errors/500.html")
		}
	})
}

func (app *App) Bootstrap() *App {
	app.SetupViews()
	app.SetupErrorHandlers()
	app.StaticWeb("/assets", "./public")
	debugStr :=   os.Getenv("APP_DEBUG")
	debug, err := strconv.ParseBool(debugStr)
	if err != nil {
		debug = false
	}
	//打印日志
	if debug == true  {
		app.Logger().SetLevel("debug")
		app.Use(recover.New())
		app.Use(logger.New())
	}
	//全局路由中间件
	app.Use(func(ctx iris.Context) {
			ctx.Next()
	})
	return app
}

func (app *App) Start(configs ...iris.Configurator) {
	port := os.Getenv("APP_PORT")
	err := app.Run(
		iris.Addr(":"+port),
		configs...,
	)
	if err != nil {
		 log.Fatal("server start fail:",err)
	}

}

func New() *App{
	appName := os.Getenv("APP_NAME")
	app:= &App{
		AppName:appName,
		AppSpawnDate:time.Now(),
		Application:iris.New(),
	}
	return app.Bootstrap()
}